package com.ywc.tool;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class SQLiteUtil extends SQLiteOpenHelper {
    private static final int SillyWhite_VERSION = 1;
    private static final String SillyWhite_NAME = "sillyWhite.db";
    private String keyString[];
    private String keyType[];
    private String tableName;
    private SQLiteDatabase sqLiteDatabase;

    public SQLiteUtil(Context context, String tableName, String keyString[], String keyType[]) {
        super(context, SillyWhite_NAME, null, SillyWhite_VERSION);
        this.tableName=tableName;
        this.keyString=keyString;
        this.keyType=keyType;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        StringBuffer stringBuffer=new StringBuffer();
        stringBuffer.append("create table if not exists ");
        stringBuffer.append(tableName);
        stringBuffer.append(" ( id integer primary key autoincrement");
        for (int i = 0; i < keyString.length; i++) {
            stringBuffer.append(" , ");
            stringBuffer.append(keyType[i]);
            stringBuffer.append(" ");
            stringBuffer.append(keyString[i]);
        }
        stringBuffer.append(" )");
        db.execSQL(stringBuffer.toString());
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String sql = "DROP TABLE IF EXISTS " + tableName;
        db.execSQL(sql);
        onCreate(db);
    }

    //开始
    private void begin()
    {
        sqLiteDatabase = getWritableDatabase();
        sqLiteDatabase.beginTransaction();
    }


    //添加
    public Long insert(ContentValues contentValues)
    {
        if (sqLiteDatabase==null)
            begin();
        return sqLiteDatabase.insert(tableName, null, contentValues);
    }

    //删除
    public int deleter( String whereClause, String[] whereArgs)
    {
        if (sqLiteDatabase==null)
            begin();
        return sqLiteDatabase.delete(tableName, whereClause, whereArgs);
    }

    //修改
    public int update(ContentValues values, String whereClause, String[] whereArgs)
    {
        if (sqLiteDatabase==null)
            begin();
        return sqLiteDatabase.update(tableName, values, whereClause,whereArgs);
    }

    //查找
    public Cursor query(String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
    {
        if (sqLiteDatabase==null)
            begin();
        return  sqLiteDatabase.query(tableName, null, null, null, null, null, null);
    }



    //数据刷新
    public void close()
    {
        if (sqLiteDatabase!=null)
        {
            sqLiteDatabase.setTransactionSuccessful();
            sqLiteDatabase=null;
        }
    }

}
